package com.kjsdfgk.hjmdsf.livev3.mvp.presenter;

import android.Manifest;
import android.app.Application;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import androidx.core.content.ContextCompat;

import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import cn.leancloud.AVObject;
import cn.leancloud.AVUser;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;
import timber.log.Timber;

import javax.inject.Inject;

import com.jess.arms.utils.PermissionUtil;
import com.kjsdfgk.hjmdsf.app.entity.FavoriteItem;
import com.kjsdfgk.hjmdsf.app.entity.HistoryItem;
import com.kjsdfgk.hjmdsf.app.entity.JJKKTokenJson;
import com.kjsdfgk.hjmdsf.app.entity.KjhfsJson;
import com.kjsdfgk.hjmdsf.app.entity.ListBean;
import com.kjsdfgk.hjmdsf.app.entity.WebPhoto;
import com.kjsdfgk.hjmdsf.livev3.mvp.contract.LiveV3Contract;

import org.litepal.LitePal;
import org.litepal.LitePalDB;

import java.io.File;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

import static com.kjsdfgk.hjmdsf.app.Config.DATA_PATH;
import static com.kjsdfgk.hjmdsf.app.Config.dbVersion;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 04/27/2020 23:28
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@ActivityScope
public class LiveV3Presenter extends BasePresenter<LiveV3Contract.Model, LiveV3Contract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public LiveV3Presenter(LiveV3Contract.Model model, LiveV3Contract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void generateDeviceUser() {
        //检测 读写文件权限
        if ( ContextCompat.checkSelfPermission(mApplication, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(mApplication, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
        ) {
            PermissionUtil.externalStorage(new PermissionUtil.RequestPermission() {
                @Override
                public void onRequestPermissionSuccess() {
                    try {
                        {
                            String deviceCode = UUID.randomUUID().toString().replace("-", "").substring(0, 15);
                            File dir = new File(DATA_PATH);
                            if (!dir.exists()) {
                                dir.mkdirs();
                            }
                            File file = new File(DATA_PATH + "tencent.dat");
                            if (!file.exists()) {
                                file.createNewFile();
                                boolean b = FileIOUtils.writeFileFromString(file, deviceCode);
                                if (b) {
                                    //    mRootView.showMessage("写入成功--->"+android);


                                }
                            } else {
                                String account = SPUtils.getInstance().getString("account", "");
                                String password = SPUtils.getInstance().getString("password", "");
                                if (!TextUtils.isEmpty(account) && !TextUtils.isEmpty(password)) {
                                }

                            }
                            String info = DeviceUtils.getManufacturer() + DeviceUtils.getModel();
                            register(deviceCode , info);
                        }


                        {
                            LitePalDB litePalDB = new LitePalDB("QQQQ", dbVersion);
                            litePalDB.setExternalStorage(true);
                            litePalDB.setStorage("Tencent");
                            litePalDB.addClassName(WebPhoto.class.getName());
                            litePalDB.addClassName(HistoryItem.class.getName());
                            litePalDB.addClassName(FavoriteItem.class.getName());
                            litePalDB.addClassName(ListBean.class.getName());

                            LitePal.use(litePalDB);
                            SQLiteDatabase db = LitePal.getDatabase();
                            System.out.println(db.getPath());
                        }

                    } catch (Exception e) {
                        mRootView.showMessage(e.toString());
                    }

                }

                @Override
                public void onRequestPermissionFailure(List<String> permissions) {

                }

                @Override
                public void onRequestPermissionFailureWithAskNeverAgain(List<String> permissions) {

                }


            }, mRootView.getRxPermissions(), mErrorHandler);



        } else {
            try {
                //已经授权时
                {
                    LitePalDB litePalDB = new LitePalDB("QQQQ", dbVersion);
                    litePalDB.setExternalStorage(true);
                    litePalDB.setStorage("Tencent");
                    litePalDB.addClassName(WebPhoto.class.getName());
                    litePalDB.addClassName(HistoryItem.class.getName());
                    litePalDB.addClassName(FavoriteItem.class.getName());
                    litePalDB.addClassName(ListBean.class.getName());
                    LitePal.use(litePalDB);
                    SQLiteDatabase db = LitePal.getDatabase();
                    System.out.println(db.getPath());
                }
                {
                    String deviceCode = UUID.randomUUID().toString().replace("-", "").substring(0, 15);
                    File dir = new File(DATA_PATH);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    File file = new File(DATA_PATH + "tencent.dat");
                    if (!file.exists()) {
                        file.createNewFile();
                        boolean b = FileIOUtils.writeFileFromString(file, deviceCode);
                    }
                    String device = FileIOUtils.readFile2String(file);
                    String info = DeviceUtils.getManufacturer() + DeviceUtils.getModel();
                    if (TextUtils.isEmpty(device)){
                        device ="AAA" + UUID.randomUUID().toString().replace("-", "").substring(0, 15);
                    }
                    String finalDevice = device;
                    AVUser.logIn(device,device).subscribe(new Observer<AVUser>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }
                        @Override
                        public void onNext(AVUser avUser) {
                            avUser.put("loginAt", TimeUtils.getNowString());
                            String account = SPUtils.getInstance().getString("account", "");
                            avUser.put("nickName",account);
                            avUser.saveInBackground().subscribe(new Observer<AVObject>() {
                                @Override
                                public void onSubscribe(Disposable d) {

                                }

                                @Override
                                public void onNext(AVObject avObject) {

                                }

                                @Override
                                public void onError(Throwable e) {

                                }

                                @Override
                                public void onComplete() {

                                }
                            });
                        }
                        @Override
                        public void onError(Throwable e) {

                            register(finalDevice, info);

                        }
                        @Override
                        public void onComplete() {

                        }
                    });

                }

            }catch (Exception e){

            }

        }

    }

    private void register(String device, String info) {
        AVUser user = new AVUser();// 新建 AVUser 对象实例
        user.setUsername(device);// 设置用户名
        user.setPassword(device);// 设置密码
        user.put("info" ,info);//
        user.put("loginAt", TimeUtils.getNowString());
        user.signUpInBackground().subscribe(new Observer<AVUser>() {
            @Override
            public void onSubscribe(Disposable d) {

            }
            @Override
            public void onNext(AVUser avUser) {
                // 注册成功，把用户对象赋值给当前用户 AVUser.getCurrentUser()

            }
            @Override
            public void onError(Throwable e) {
                // 失败的原因可能有多种，常见的是用户名已经存在。

            }
            @Override
            public void onComplete() {

            }
        });

    }


    public void getKjhfsData() {

        ListBean bean = LitePal.where().order("version desc").findFirst(ListBean.class);
        if (bean == null || bean.getVersion() == 0){
            mModel.getKjhfsData(100)
                    .subscribeOn(Schedulers.io())
                    .retryWhen(new RetryWithDelay(3, 2))
                    .subscribe(new ErrorHandleSubscriber<KjhfsJson>(mErrorHandler) {
                        @Override
                        public void onError(@NonNull Throwable e) {
                           Timber.tag(TAG).d(e);
                        }

                        @Override
                        public void onNext(@NonNull KjhfsJson result) {

                             LitePal.saveAll(result.getData());
                             List<ListBean> listBeans = LitePal.findAll(ListBean.class);
                            Timber.tag(TAG).d(listBeans.toString());

                        }
                    });
        } else {
            mModel.getKjhfsData(bean.getVersion()+1)
                    .subscribeOn(Schedulers.io())
                    .retryWhen(new RetryWithDelay(3, 2))
                    .subscribe(new ErrorHandleSubscriber<KjhfsJson>(mErrorHandler) {
                        @Override
                        public void onError(@NonNull Throwable e) {
                            Timber.tag(TAG).d(e);
                        }

                        @Override
                        public void onNext(@NonNull KjhfsJson result) {

                            LitePal.saveAll(result.getData());
                            List<ListBean> listBeans = LitePal.findAll(ListBean.class);
                            Timber.tag(TAG).d(listBeans.toString());


                        }
                    });
        }
    }
}
